<template>
  <div class="app-container">
    <el-row :gutter="30">
      <el-col :span="24">
        <div style="margin-top:10px">
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="addData">新增</el-button>
          <el-button icon="el-icon-close" type="danger" size="mini" @click="deleteAny">删除</el-button>
        </div>
        <div class="query-form">
          <el-form ref="tableSearchParam" :model="tableSearchParam" label-width="50px" :inline="true">
            <el-form-item label="名称" label-width="50px">
              <el-input v-model="tableSearchParam.insuranceClassifyName" style="width:200px" size="small"
                        clearable></el-input>
            </el-form-item>
            <el-form-item label="行业" :label-width="formLabelWidth" prop="name">
              <el-select v-model="tableSearchParam.industryIds" placeholder="请选择" no-data-text="暂无数据"
                         style="width:200px" multiple>
                <el-option
                  v-for="item in allIndustry"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="listTableData" icon="el-icon-search" size="small">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <br/>
        <el-table
          ref="userTable"
          :data="tableData"
          border
          empty-text="暂无数据"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="35">
          </el-table-column>
          <el-table-column
            label="名称"
            property="insuranceClassifyName"
            width="100">
          </el-table-column>
          <el-table-column
            label="订单通知模板"
            width="120">
            <template slot-scope="scope">
              {{scope.row.messageTemplateId == null || scope.row.messageTemplateId == '' ? '未设置' : scope.row.messageTemplateName}}
            </template>
          </el-table-column>
          <el-table-column
            label="可使用行业"
            property="industry"
            width="95">
          </el-table-column>
          <el-table-column
            label="分成策略"
            property="address">
            <template slot-scope="scope">
              {{covertDividedStrategy(scope.row.dividedStrategy)}}
            </template>
          </el-table-column>
          <el-table-column
            label="照片上传约束"
            width="170">
            <template slot-scope="scope">
              {{covertUploadConstraint(scope.row.uploadConstraint)}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="450">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-edit"
                type="success"
                @click="editData(scope.$index, scope.row)">编辑
              </el-button>
              <el-button
                size="mini"
                icon="el-icon-edit"
                @click="editStrategy(scope.$index, scope.row)">设置分成策略
              </el-button>
              <el-button
                size="mini"
                icon="el-icon-edit"
                @click="editUploadConstraint(scope.$index, scope.row)">照片上传约束
              </el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-close"
                v-if="scope.row.id!='e7cec11e64a7459e8d096a706458d1f8' && scope.row.id!='8b14ef2abd544815a5ed45133b489ebb'"
                @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page=this.currentPage
            :page-sizes="[10, 20, 30, 40]"
            :page-size=this.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total=this.total>
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title="actionType=='add'?'新增保险分类':'修改保险分类'" :visible.sync="dialogFormVisible" top="10vh">
      <el-form :model="formData" style="width:400px" :rules="rules" ref="ruleForm">
        <el-form-item label="名称" :label-width="formLabelWidth" prop="insuranceClassifyName">
          <el-input v-model="formData.insuranceClassifyName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="行业" :label-width="formLabelWidth" prop="name">
          <el-select v-model="formData.industryIds" placeholder="请选择" no-data-text="暂无数据"
                     style="width:200px" multiple>
            <el-option
              v-for="item in allIndustry"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单通知模板" :label-width="formLabelWidth" prop="messageTemplateId">
          <!--prop="messageTemplateId"-->
          <el-select v-model="formData.messageTemplateId" style="width:290px">
            <el-option
              v-for="item in allMessageTemplate"
              :value="item.id"
              :key="item.id"
              :label="item.messageTemplateName">

            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="照片上传约束" :label-width="formLabelWidth">
          <el-checkbox-group v-model="uploadConstraintArr" @change="checkChange">
            <el-checkbox label="pz">是否可拍照</el-checkbox>
            <el-checkbox label="xc">是否可从相册选取</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="服务协议" :label-width="formLabelWidth" prop="protocol">
          <el-input type="textarea" v-model="formData.protocol" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdd" v-if="actionType=='add'" :loading="loading">保存</el-button>
        <el-button type="primary" @click="handleEdit" v-else :loading="loading">修改</el-button>
      </div>
    </el-dialog>
    <el-dialog title="设置分成策略" :visible.sync="dialogStrategyAFormVisible" top="10vh" width="55%">
      <div style="margin-top:10px;margin-bottom: 10px">
        <el-button icon="el-icon-plus" type="primary" size="mini" @click="addStrategyData">新增</el-button>
        <el-button icon="el-icon-close" type="danger" size="mini" @click="deleteStrategyAny">删除</el-button>
      </div>
      <el-table
        :data="strategyFormDatas"
        border
        empty-text="暂无数据"
        style="width: 100%"
        @selection-change="handleStrategySelectionChange">
        <el-table-column
          type="selection"
          width="35">
        </el-table-column>
        <el-table-column
          label="服务商"
          property="roleName">
        </el-table-column>
        <el-table-column
          label="分成"
          property="shared">
        </el-table-column>
        <el-table-column
          label="积分"
          property="integral">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              type="success"
              @click="editStrategyData(scope.$index, scope.row)">编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="actionStrategyType=='add'?'新增分成策略':'分成策略'" :visible.sync="dialogStrategyBFormVisible" top="10vh"
               width="55%">
      <el-form :model="strategyFormData" ref="operationRuleForm">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="服务商" :label-width="formLabelWidth">
              <el-select v-model="strategyFormData.role" placeholder="请选择" style="width:300px"
                         @change="roleSelectChange" :disabled="actionStrategyType=='edit'">
                <el-option
                  v-for="item in allServiceProdiver"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="金额分成" :label-width="formLabelWidth">
              <el-input-number v-model="strategyFormData.shared" :precision="2" :step="0.01"
                               style="width:300px"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="积分分成" :label-width="formLabelWidth">
              <el-input-number v-model="strategyFormData.integral" :precision="0" :step="1"
                               style="width:300px"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogStrategyBFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleStrategyAdd" v-if="actionStrategyType=='add'" :loading="loading">保存
        </el-button>
        <el-button type="primary" @click="handleStrategyEdit" v-else :loading="loading">修改</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改照片上传约束" :visible.sync="dialogUploadConstraintFormVisible" top="10vh">
      <el-form :model="formUploadConstraintData" style="width:400px" :rules="rules" ref="ruleForm">
        <el-form-item label="照片上传约束" :label-width="formLabelWidth">
          <el-checkbox-group v-model="formUploadConstraintData.uploadConstraintArr" @change="checkChange">
            <el-checkbox label='pz'>是否可拍照</el-checkbox>
            <el-checkbox label='xc'>是否可从相册选取</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUploadConstraintFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUploadConstraint">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  .page {
    text-align: center;
    margin-top: 20px;
  }

  .query-form {
    border-bottom: 1px solid #ebeef5;
    padding-top: 25px;
  }

  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 10px;
  }
</style>

<script>
  import insuranceClassifyApi from '@/api/insuranceClassifyApi'
  import messageTemplateApi from '@/api/messageTemplateApi'
  import industryApi from '@/api/industryApi'
  export default {

    created() {
      messageTemplateApi.listAll((res) => {
        this.allMessageTemplate = res
      }, () => {
      })
      industryApi.listAll((res) => {
        this.allIndustry = res
      }, () => {
      })
      this.initData()
    },

    data() {
      return {
        dialogUploadConstraintFormVisible: false,
        formUploadConstraintData: {
          uploadConstraintArr: []
        },
        allMessageTemplate: [],
        uploadConstraintArr: [],
        allIndustry:[],
        options: [],
        dialogStrategyAFormVisible: false,
        dialogStrategyBFormVisible: false,
        formsData: {
          templateId: ''
        },
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        tableSearchParam: {
          insuranceClassifyName: '',
          industryIds: []
        },
        dialogFormVisible: false,
        formLabelWidth: '110px',
        formData: {
          insuranceClassifyName: '',
          messageTemplateId: '',
          industryIds: []
        },
        actionStrategyType: 'add',
        handleId: '',
        strategyFormDatas: [],
        strategyFormData: {
          role: '',
          roleName: '',
          shared: '',
          integral: ''
        },
        multipleStrategySelection: [],
        loading: false,
        actionType: '',
        multipleSelection: [],
        rules: {
          insuranceClassifyName: [
            {required: true, message: '请输入保险分类名称', trigger: 'blur'}
          ],
          messageTemplateId: [
            {required: true, message: '请选择订单通知模板', trigger: 'change'}
          ],
          protocol: [
            {required: true, message: '请填写服务协议', trigger: 'blur'}
          ],
          uploadConstraintArr: [
            {required: true, message: '请勾选照片上传约束', trigger: 'blur'}
          ]
        },
        insuranceClassifyId: '',
        uploadConstraint: {
          is_taking_pictures: 0,
          is_photo: 0
        },
        allServiceProdiver: [
          {
            id: '811f820613394fc481612a47282e5f8f',
            name: '救援司机'
          },
          {
            id: 'e300c4bd7df24fa3a57955893f349965',
            name: '救援公司'
          },
          {
            id: '73630d394fcb4a6dbc38c43284b0e23d',
            name: '救援代理'
          }
        ],
      }
    },
    methods: {
      editUploadConstraint(index, row) {
        this.formData.id = row.id
        this.formUploadConstraintData.uploadConstraintArr = []
        if (row.uploadConstraint != null) {
          if (row.uploadConstraint.is_photo == '1')
            this.formUploadConstraintData.uploadConstraintArr.push('xc')
          if (row.uploadConstraint.is_taking_pictures == '1')
            this.formUploadConstraintData.uploadConstraintArr.push('pz')
        }

        this.dialogUploadConstraintFormVisible = true
      },
      handleUploadConstraint() {
        if (this.formUploadConstraintData.uploadConstraintArr.length == 0) {
          this.$message({
            message: '请选择照片上传约束',
            type: 'warning'
          })
          return
        }
        insuranceClassifyApi.setUploadConstraint(this.formData.id, this.formData, (res) => {
          this.$message({
            message: '更新成功',
            type: 'success'
          })
          this.dialogUploadConstraintFormVisible = false
          this.initData()
        }, () => {
        })
      },
      checkChange(value) {
        if (value.indexOf('pz') != -1) {
          this.uploadConstraint.is_taking_pictures = '1'
        } else {
          this.uploadConstraint.is_taking_pictures = '0'
        }

        if (value.indexOf('xc') != -1) {
          this.uploadConstraint.is_photo = '1'
        } else {
          this.uploadConstraint.is_photo = '0'
        }

        this.formData.uploadConstraint = this.uploadConstraint
      },
      covertDividedStrategy(dividedStrategy) {
        if (dividedStrategy == null || dividedStrategy != null && dividedStrategy.length == 0) return '未设置'
        let ret = ''
        for (var dd of dividedStrategy) {
          ret += dd.roleName + dd.shared + '元' + dd.integral + '积分' + ','
        }
        if (ret != '') {
          ret = ret.substring(0, ret.length - 1)
        }
        return ret
      },
      covertUploadConstraint(uploadConstraint) {
        if (uploadConstraint == null) return '未设置'
        const code = uploadConstraint.is_taking_pictures + uploadConstraint.is_photo
        let ret = ''
        switch (code) {
          case '00':
            ret = '不可拍照上传，不可相册上传'
            break
          case '01':
            ret = '不可拍照上传，可相册上传'
            break
          case '10':
            ret = '可拍照上传，不可相册上传'
            break
          case '11':
            ret = '可拍照上传，可相册上传'
            break
          default:
            ret = ''
            break
        }

        return ret
      },
      initData() {
        this.listTableData()
      },
      listTableData() {
        insuranceClassifyApi.list(this.tableSearchParam, this.currentPage, this.pageSize, (res) => {
          this.tableData = res.list
          this.total = res.total
        }, () => {
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.listTableData()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.listTableData()
      },
      addData() {
        //清空历史值
        this.formData = {
          insuranceClassifyName: '',
          messageTemplateId: '',
          industryIds: []
        }
        this.uploadConstraintArr = []
        this.actionType = 'add'
        this.dialogFormVisible = true
        this.$refs['ruleForm'].resetFields()
      },
      handleAdd() {
        if (this.uploadConstraintArr.length == 0) {
          this.$message({
            message: '请选择照片上传约束',
            type: 'warning'
          })
          return
        }
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            insuranceClassifyApi.add(this.formData, (res) => {
              this.loading = false
              this.dialogFormVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.initData()
            }, () => {
              this.loading = false
            })
          }
        })
      },
      editData(index, row) {
        //清空历史值
        this.formData = {
          insuranceClassifyName: '',
          messageTemplateId: '',
          uploadConstraintArr: [],
          industryIds: []
        }
        let that = this
        that.actionType = 'edit'
        this.loading = true
        insuranceClassifyApi.get(row.id, (res1) => {
          that.formData = res1
          that.formData.id = row.id
          that.formData.industryIds = res1.industryIds || []
          this.uploadConstraintArr = []
          if (res1.uploadConstraint.is_photo == '1') {
            this.uploadConstraintArr.push('xc')
          }
          if (res1.uploadConstraint.is_taking_pictures == '1') {
            this.uploadConstraintArr.push('pz')
          }
          this.loading = false
          that.dialogFormVisible = true
        }, () => {

        })
      },
      handleEdit() {
        if (this.uploadConstraintArr.length == 0) {
          this.$message({
            message: '请选择照片上传约束',
            type: 'warn'
          })
          return
        }
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            insuranceClassifyApi.update(this.formData.id, this.formData, (res) => {
              this.loading = false
              this.dialogFormVisible = false
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.initData()
            }, () => {
              this.loading = false
            })
          }
        })
      },
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          insuranceClassifyApi.deleteSingleInsuranceClassify(row.id, (res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initData()
          }, () => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleSelectionChange(val) {
        this.multipleSelection = []
        for (var ms of val) {
          if (ms.id === 'e7cec11e64a7459e8d096a706458d1f8' || ms.id === '8b14ef2abd544815a5ed45133b489ebb') {
            this.$refs.userTable.toggleRowSelection(ms, false)
            continue
          }
          this.multipleSelection.push(ms.id)
        }
      },
      deleteAny() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            type: 'warning',
            message: '请选择记录!'
          })
          return;
        }
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          insuranceClassifyApi.remove(this.multipleSelection, (res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initData()
          }, () => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      roleSelectChange(v) {
        for (var o of this.allServiceProdiver) {
          if (o.id == v) {
            this.strategyFormData.role = o.id
            this.strategyFormData.roleName = o.name
            break
          }
        }
      },
      editStrategy(index, row) {
        this.insuranceClassifyId = row.id
        if (row.dividedStrategy != null) {
          this.strategyFormDatas = row.dividedStrategy
        } else {
          this.strategyFormDatas = []
        }

        this.dialogStrategyAFormVisible = true
      },
      addStrategyData() {
        this.strategyFormData = {
          role: '',
          roleName: '',
          shared: '',
          integral: ''
        }
        this.actionStrategyType = 'add'
        this.dialogStrategyBFormVisible = true
      },
      handleStrategyAdd() {
        if (this.checkStrategy(this.strategyFormData.role)) {
          this.$message({
            type: 'warning',
            message: '该服务商角色已添加!'
          })
          return
        }
        this.strategyFormDatas.push(this.strategyFormData)
        this.dialogStrategyBFormVisible = false
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
      },
      checkStrategy(role) {
        for (var sf of this.strategyFormDatas) {
          if (sf.role == role) {
            return true
          }
        }
        return false
      },
      editStrategyData(index, row) {
        for (const s of this.strategyFormDatas) {
          if (s.role === row.role) {
            this.handleId = row.role
            let qqstrategyFormData = {
              role: '',
              roleName: '',
              shared: '',
              integral: ''
            }
            qqstrategyFormData.role = s.role
            qqstrategyFormData.roleName = s.roleName
            qqstrategyFormData.shared = s.shared
            qqstrategyFormData.integral = s.integral
            this.strategyFormData = qqstrategyFormData
            this.actionStrategyType = 'edit'
            this.dialogStrategyBFormVisible = true
            break
          }
        }
      },
      handleStrategyEdit() {
        let index = 0;
        for (const s of this.strategyFormDatas) {
          if (s.role === this.handleId) {
            this.strategyFormDatas.splice(index, 1)
            this.strategyFormDatas.push(this.strategyFormData)
            this.dialogStrategyBFormVisible = false
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            break
          }
          index++
        }
      },
      handleStrategySelectionChange(val) {
        this.multipleStrategySelection = []
        for (var ms of val) {
          this.multipleStrategySelection.push(ms.role)
        }
      },
      deleteStrategyAny() {
        if (this.multipleStrategySelection.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择记录!'
          })
          return
        }
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          for (const m of this.multipleStrategySelection) {
            let i = 0
            for (const s of this.strategyFormDatas) {
              if (s.role === m) {
                this.strategyFormDatas.splice(i, 1)
                break
              }
              i++
            }
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      handleSave() {
        let param = {
          dividedStrategy: this.strategyFormDatas
        }
        insuranceClassifyApi.setDividedStrategy(this.insuranceClassifyId, param, (res) => {
          this.$message({
            type: 'success',
            message: '设置成功!'
          })
          this.dialogStrategyAFormVisible = false
          this.initData()
        }, () => {
        })
      }
    }
  }
</script>
